package cn.gok.lambda;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class 常用的函数式接口 {
    public static void main(String[] args) {
        //Runable接口();
//        doRun(()->{
//            System.out.println("xxx");
//        });

        //Consumer接口();
        // Funtion接口();
        
        //Supplier接口();
        //PreDicate接口();
        简化lambda();
    }

    private static void 简化lambda() {
        Consumer<String> con = System.out::println;
    }

    private static void PreDicate接口() {
        //有1个入参，有一个boolean返回值
        Predicate<Integer> predicate = i->i>=100;
        System.out.println(predicate.test(99));
        System.out.println(predicate.test(101));
        Predicate<Integer> predicate12 = i->i%2==0;
        System.out.println(predicate.or(predicate12).test(98));
    }

    private static void Supplier接口() {
        //没有入参，有返回值。泛型是返回值类型。
        Supplier<String> sup = ()-> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println("执行结果:" + sup.get());
    }

    private static void Funtion接口() {
        //1个入参，有返回。
        Function<String,Integer> function1 = str ->str.length();
        System.out.println(function1.apply("战神学Java"));
        //函数的接连调用
        Function<Integer,Integer> function2 = i->i+100;
        System.out.println(function2.compose(function1).apply("战神学Java"));
        //获得入参float的平方
        Function<Float,Float> function3 = i->i*i;
        System.out.println(function3.apply(10.0f));
        Function<Float,Float> function4 = i->i*100;
        System.out.println(function4.apply(10.0f));
    }

    private static void Consumer接口() {
        //有1个入参，没有返回值
        Consumer<String> con1 = (String str)->{
            str+="战神";
            System.out.println("第一个结果:"+str);
        };
        Consumer<String> con2 = (String str)->{
            str+="*";
            System.out.println("第二个结果:"+str);
        };
        //采用accept执行lambda
        con1.accept("abc");
        //两次消费，再执行一次第一个结果
        con1.andThen(con2).accept("abc");
    }

    private static void doRun(Runnable r) {
        r.run();
    }

    private static void Runable接口() {
        //jdk1.8之前
        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                System.out.println("!!!");
            }
        };
        runnable.run();
//        Runnable r2 = () ->{
//            System.out.println("!!!");
//        };
//        r2.run();
    }

}
